package test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public class SpinLock {

    private AtomicReference<Thread> tReference = new AtomicReference<>();

    public void lock() {
        Thread curThread = Thread.currentThread();
        //为null表示没有线程占用锁
        while (!tReference.compareAndSet(null, curThread)) {
            //死循环
        }
    }

    public void unlock() {
        tReference.set(null);
    }

    public static void main(String[] args) {
        SpinLock lock = new SpinLock();
        new Thread(() -> {
            lock.lock();
            System.out.println("A Thread get the lock");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println("A unlock");
                lock.unlock();
            }
        }).start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            lock.lock();
            try {
            System.out.println("B Thread get the lock");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                System.out.println("B unlock");
                lock.unlock();
            }
        }).start();

    }
}
